from typing import Any, Dict
from datetime import datetime
import json
import os
from .ppt_generator import PPTGenerator
from config.settings import settings

class ToolRegistry:
    """A registry for managing and executing tools."""
    
    def __init__(self):
        self._tools: Dict[str, callable] = {}
        self._ppt_generator = None
        self.register_default_tools()

    @property
    def ppt_generator(self):
        if self._ppt_generator is None and settings.DEEPSEEK_API_KEY:
            self._ppt_generator = PPTGenerator(settings.DEEPSEEK_API_KEY)
        return self._ppt_generator

    def register_tool(self, name: str, tool_func: callable):
        """Register a new tool."""
        self._tools[name] = tool_func

    def get_tool(self, name: str) -> callable:
        """Get a tool by name."""
        return self._tools.get(name)

    def list_tools(self) -> list:
        """List all available tools."""
        return list(self._tools.keys())

    def register_default_tools(self):
        """Register default tools."""
        # Example tools
        self.register_tool("get_current_time", self.get_current_time)
        self.register_tool("echo", self.echo)
        self.register_tool("json_parser", self.json_parser)
        self.register_tool("generate_ppt", self.generate_ppt)

    @staticmethod
    def get_current_time(*args, **kwargs) -> str:
        """Get current time."""
        return datetime.now().isoformat()

    @staticmethod
    def echo(text: str, *args, **kwargs) -> str:
        """Echo the input text."""
        return text

    @staticmethod
    def json_parser(text: str, *args, **kwargs) -> Dict:
        """Parse JSON string to dictionary."""
        try:
            return json.loads(text)
        except json.JSONDecodeError as e:
            return {"error": str(e)}

    def generate_ppt(self, topic: str, output_filename: str = None, *args, **kwargs) -> Dict[str, Any]:
        """Generate a PPT presentation for the given topic."""
        if not self.ppt_generator:
            return {"error": "PPT Generator not initialized. Please check DEEPSEEK_API_KEY."}

        try:
            # Create output directory if it doesn't exist
            os.makedirs(settings.PPT_OUTPUT_DIR, exist_ok=True)

            # Generate output filename if not provided
            if not output_filename:
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                output_filename = f"{topic.replace(' ', '_')}_{timestamp}.pptx"

            output_path = os.path.join(settings.PPT_OUTPUT_DIR, output_filename)
            
            # Generate the presentation
            final_path = self.ppt_generator.generate_ppt(topic, output_path)
            
            return {
                "status": "success",
                "file_path": final_path,
                "message": f"Presentation generated successfully at {final_path}"
            }

        except Exception as e:
            return {
                "status": "error",
                "error": str(e)
            }

    def execute_tool(self, tool_name: str, *args, **kwargs) -> Any:
        """Execute a tool by name with given arguments."""
        tool = self.get_tool(tool_name)
        if not tool:
            raise ValueError(f"Tool not found: {tool_name}")
        return tool(*args, **kwargs) 